<template>
	<el-container v-loading="loading">
		<el-header style="height: auto;padding: 10px 10px;">
			<div class="left-panel">
				<sc-select-filter :data="filterData" :label-width="80" @on-change="tabChange">
				</sc-select-filter>
			</div>
			<div class="right-panel">
				<div class="left-panel">
					<fsButton ref="button" plain size="small" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
				</div>
				<div class="right-panel">
					<ex-search ref="search" :searches="searches" @searchOk="searchHandler" :fixedParam="{}"></ex-search>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding reportSummaryTable" style="padding: 0 5px;">
			<el-table id="allocateTable" :data="assetData" :span-method="rowSpanMethod" border style="width: 100%">
				<template v-for="column in this.columns" :key="column.code">
					<el-table-column :prop="column.code"
									 :label="column.name"
									 :formatter="this.formatters"
									 :sortable="column.sortable?column.sortable:false"
									 :column-key="column.code"
									 :show-overflow-tooltip="true"
									 :align="'center'"
									 :width="column.width?column.width:null">
					</el-table-column>
				</template>
			</el-table>
		</el-main>
	</el-container>
	<data-card ref="dataCard"></data-card>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import scSelectFilter from "@/components/scSelectFilterLink/index.vue";
import tool from "@/utils/tool";
import DataCard from "@/views/asset/card/card.vue";
import scEcharts from "@/components/scEcharts/index.vue";
import print from "@/utils/print";
import globalparam from "@/constant/model/globalparam";
import {h} from "vue";
import {ElButton, ElContainer} from "element-plus";
import moment from "moment";
export default {
	name: '调拨统计',
	components: {
		scEcharts,
		DataCard,
		scSelectFilter,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			apiObj: [],
			buttons: [
				{name: "导出", icon: "el-icon-download", click: "export",  type: "info", permission: "export"},
				{name: "打印", icon: "el-icon-download", click: "printTable",  type: "info", permission: "print"},
			],
			searches: [
				{type: "tree-select", name: "使用部门", code: "deptIds", placeholder: "请选择使用部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.readDeptIds()},
				{type: "tree-select", name: "资产类别", code: "assetCategoryIds", placeholder: "请选择资产类别", dictCode:'FamsAssetCategory',checkStrictly:true,multiple:true,dataPermissionProcess:true},
				{type: "daterange", name: "调拨日期", code: "zcdbDateStart,zcdbDateEnd", placeholder: "请选择调拨日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:30},
			],
			columns: [
				{code: "name", name: "部门名称",click:"show", width:""},
				{code: "assetCount", name: "调拨数量", width:"180"},
				{code: "operationCount", name: "调拨次数", width:"180"},
				{code: "originalValue", name: "原值", width:"200"},
				{code: "netValue", name: "净值", width:"180"},
			],
			filterData: [
				{
					title: "统计方式",
					key: "assetStatisticsType",
					multiple: false,
					options: [
						{
						label: "按使用部门统计",
						value: "1"
						},
						{
							label: "按资产分类统计",
							value: "2"
						},
					]
				},
			],
			parentLevelCode:"",
			assetIds:[],
			loading: false,
			assetData:[],
			assetStatisticsType: "1",
			excludeStatus:['delete'],
			assetStatisticsRange: "",
			readDeptIds: this.$TOOL.current.readDeptIds(),
			// manageDeptIds: this.$TOOL.current.manageDeptIds(),
			manageCategoryIds: this.$TOOL.current.manageAssetCategoryIds(),
			loginUsers: this.$TOOL.current.user(),
		}
	},
	created() {
	},
	mounted() {
		this.$cache.data.loadGlobalParam(globalparam.assetStatisticsRange.paramCode).then((res) => {
			this.assetStatisticsRange = res;
			this.searchHandler();
		});
	},
	beforeMount() {
	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		async searchHandler() {
			this.loading = true;
			//释放搜索组件的loading状态
			if (this.$refs.search) {
				this.$refs.search.setLoading(true);
			}
			this.$refs.search.drawer=false;
			let queryParams = {}
			this.formatQueryParams(queryParams,this);
			let rsp = await this.$API.asset.assetLog.countAllocateTimes.post(queryParams);
			if(rsp.code === 2000 && rsp.data){
				this.assetData = rsp.data;
				//释放搜索组件的loading状态
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
				this.loading = false;
			}else{
				this.loading = false;
				//释放搜索组件的loading状态
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
			}
		},
		//导出
		async export(_this,index) {
			_this.$refs.button.loading(index, true);
			let queryParams = {}
			_this.formatQueryParams(queryParams,_this);
			queryParams.exportType = "newAllocate";
			let res = await _this.$API.asset.assetLog.export.post(queryParams);
			if (res.code === 2000) {
				await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
			}
			_this.$refs.button.loading(index, false);
		},
		//合并表格最后一行单元格
		rowSpanMethod(row){
			if (row.rowIndex === this.assetData.length - 1) {
				if (row.columnIndex === 0) {
					return {
						rowspan: 1, // 合并几行
						colspan: 2, // 合并几列
					};
				}else if(row.columnIndex === 1){
					return {
						rowspan: 1, // 合并几行
						colspan: 3, // 合并几列
					};
				}
			}
		},
		//标签切换
		async tabChange(name){
			this.assetStatisticsType = name.assetStatisticsType;
			if(this.assetStatisticsType === '1'){
				this.columns[0].name = '部门名称'
			}
			if(this.assetStatisticsType === '2'){
				this.columns[0].name = '资产类型'
			}
			await this.searchHandler();
		},
		printTable(){
			let printContent = document.getElementById("allocateTable");
			print(printContent);
		},
		show(_this,row){
			let queryParams = {};
			if(!queryParams.zcdbDateStart){
				queryParams.zcdbDateStart = "20000101";
			}
			if(!queryParams.zcdbDateEnd){
				queryParams.zcdbDateEnd = moment(new Date()).format("YYYYMMDD");
			}
			_this.loading = true;
			queryParams.documentType = 'allocate';
			queryParams.documentStatus = 'executed';
			_this.formatQueryParams(queryParams,_this);
			if(queryParams.isFirstQuery){
				if(_this.assetStatisticsType === "1") {
					let deptQuery = {};
					deptQuery.pathCode = row.pathCode;
					deptQuery.levelCode = row.levelCode
					deptQuery.ids = _this.readDeptIds;
					_this.$API.system.dept.findManageAllChild.post(deptQuery).then((rsp)=>{
						if(rsp.code === 2000 && rsp.data){
							if(rsp.data){
								queryParams.usingDepartmentIds = rsp.data;
							}else{
								queryParams.usingDepartmentIds = [];
							}
							queryParams.usingDepartmentIds = rsp.data;
							queryParams.usingDepartmentIds.push(row.id)
							_this.searchAsset(row.name,queryParams);
							_this.loading = false;
						}
					});
				}else if(_this.assetStatisticsType === "2"){
					let categoryQuery = {};
					categoryQuery.pathCode = row.pathCode;
					categoryQuery.levelCode = row.levelCode
					categoryQuery.ids = _this.manageCategoryIds;
					_this.$API.asset.assetcategory.findManageAllChild.post(categoryQuery).then((rsp)=>{
						if(rsp.code === 2000 && rsp.data){
							if(rsp.data){
								queryParams.assetCategoryIds = rsp.data;
							}else{
								queryParams.assetCategoryIds = [];
							}
							queryParams.assetCategoryIds.push(row.id)
							_this.searchAsset(row.name,queryParams);
							_this.loading = false;
						}
					});
				}
			}else{
				if(_this.assetStatisticsType === "1") {
					queryParams.usingDepartmentId = row.id;
				}else if(_this.assetStatisticsType === "2"){
					queryParams.assetCategoryId = row.id;
				}
				_this.searchAsset(row.name,queryParams);
				_this.loading = false;
			}

		},
		searchAsset(item,queryParams) {
			let title = "调拨统计"+item+"资产履历明细";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = this.$TOOL.crypto.MD5(title);//可以做为key的关键字段或内容
			/**
			 *  1 = 根据管理部门，根据登录账户管理范围，资产的管理部门在账户管理范围内的显示<br>
			 *  2 = 根据使用部门，根据登录账户管理范围，资产的使用部门在账户管理范围内的显示<br>
			 *  3 = 根据管理部门或使用部门，根据登录账户管理范围，资产的使用部门或管理部门在账户管理范围内的显示<br>
			 *  其它 = 根据管理部门，按台账，根据使用部门或管理部门或借用部门在管理范围内的
			 */
			//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
					assetStatisticsRange:queryParams.assetStatisticsRange,
					deptIds:queryParams.deptIds,
					assetCategoryIds:queryParams.assetCategoryIds,
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
				searchParams: queryParams
			};
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toAssetLogByGroup",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		formatQueryParams(queryParams,_this){
			queryParams.assetStatisticsType = _this.assetStatisticsType;
			Object.assign(queryParams, _this.$refs.search.searchParams());
			if(_this.assetStatisticsType === '1'){
				queryParams.assetStatisticsRange = '2';
			}else{
				queryParams.assetStatisticsRange = _this.assetStatisticsRange;
			}
			if(!queryParams.deptIds||queryParams.deptIds.length===0){
				queryParams.deptIds = [];
				if(_this.assetStatisticsType === '1'){
					queryParams.isFirstQuery = "true";
				}
				queryParams.deptIds = _this.readDeptIds;
			}
			if(!queryParams.assetCategoryIds||queryParams.assetCategoryIds.length===0){
				if(_this.assetStatisticsType === '2'){
					queryParams.isFirstQuery = "true";
				}
				queryParams.assetCategoryIds = _this.manageCategoryIds;
			}
			queryParams.excludeStatus = _this.excludeStatus;
		},
		formatters(row, column, cellValue, index) {
			for (const item of this.columns) {
				if (item.code === column.property){
					if (item.click) {
						if (item.fixedValue) {
							cellValue = item.fixedValue;
						} else {
							if (item.formatter) {
								if (item.formatter instanceof Function) {
									cellValue = item.formatter(row, cellValue, this);
								} else {
									cellValue = tool.format.convert(cellValue, item.formatter, item.key);
								}
							}
						}
						let label = cellValue+'';
						let clicks = item.click.split(',');
						let labels = label.split(',');
						let permissions = [];
						if (item.permissions) {
							permissions = item.permissions.split(',');
							// permissions.splice(permissions.indexOf(''), 1);
						}
						let children = [];
						if(index < (this.assetData.length - 2) ){
							clicks.forEach((click, index) => {
								let elBtn = h(ElButton, {
									link: true,
									type: 'primary',
									style: {margin: 'auto'},
									size: 'small',
									["onClick"]: () => {
										this.$options.methods[click](this, row);
										// this.$emit('columnClick', click, row);
									}
								}, () => labels[index])
								if (permissions.length > 0) {
									if (permissions.filter(item => item === click).length > 0) {
										children.push(elBtn);
									}
								} else {
									children.push(elBtn);
								}
							});
						}else{
							return cellValue;
						}
						// cellValue = h(ElButton,{link:true,type:'primary',size:'small',["onClick"]:()=>{ this.$emit('columnClick',item.click,row);}},()=>label);
						cellValue = h(ElContainer, {key: tool.uuid("elk"), style: {display: 'flex'}}, () => children);
					}else{
						if (item.formatter) {
							if (item.formatter instanceof Function) {
								cellValue = item.formatter(row, cellValue, this, index);
							} else {
								cellValue = tool.format.convert(cellValue, item.formatter, item.key);
							}
						}
					}
				}

			}
			return cellValue;
		},
	}
}

</script>
<style scoped>

</style>
